package array;

/**
 * 给定一个n个元素有序的（升序）整型数组nums 和一个目标值target，
 * 写一个函数搜索nums中的 target，如果目标值存在返回下标，否则返回 -1。
 *
 */
public class leetcode704_search {

    public static void main(String[] args) {
        int[] aa = {-1,4,5,2,6,7,33,64};
        leetcode704_search leetcode704_search = new leetcode704_search();
        int search = leetcode704_search.search2(aa, -1);
        System.out.println(search);
    }

    public int search(int[] nums, int target) {
        if(nums == null || nums.length == 0){
            return -1;
        }
        int start = 0;
        int end = nums.length - 1;
        while(start <= end){
            int mid = start + ((end - start)/2);
            if(nums[mid] > target){
                end = mid - 1;
            }else if(nums[mid] < target){
                start = mid + 1;
            }else{
                return mid;
            }
        }

        return -1;

    }

    public int search2(int[] nums, int target) {

        int length = nums.length;
        int start = 0;
        int end = length - 1;
        while (start <= end){
            int mid = ((end - start)/2) + start;
            if(nums[mid] == target){
                return mid;
            }else if(nums[mid] > target){
                end = mid - 1;
            }else if(nums[mid] < target){
                start = mid + 1;
            }
        }
        return -1;


    }

    public int search3(int[] nums, int target) {
        if(nums == null || nums.length == 0) return 0;
        if(nums.length == 1){
            return nums[0] == target ? 0 : -1;
        }
        int start = 0;
        int end = nums.length - 1;
        while(start < end){
            int mid = start + (end - start)/2;
            if(nums[mid] < target){
                start = mid + 1;
            }else{
                end = mid;
            }
        }
        return nums[start] == target ? start : -1;

    }

}
